package com.kalvan.web.exception;

import com.kalvan.core.exception.BizException;
import com.kalvan.web.i18n.MessageResourceExtension;
import com.kalvan.web.servlet.response.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

/**
 * @author chenliang
 */
@RestController
@ControllerAdvice
@Slf4j
public class ExceptionHandle extends ResponseEntityExceptionHandler implements ApplicationContextAware {

    @Autowired
    private MessageResourceExtension messageSource;

    ApplicationContext applicationContext;

    /**
     * @param arg0
     * @throws BeansException
     */
    @Override
    public void setApplicationContext(ApplicationContext arg0) throws BeansException {
        applicationContext = arg0;
    }

    /**
     * 重写handleExceptionInternal，自定义处理过程
     */
    @Override
    protected ResponseEntity<Object> handleExceptionInternal(Exception ex, Object body, HttpHeaders headers, HttpStatus status, WebRequest request) {
        return errorHandler(ex);
    }

    /**
     * 异常捕获
     * HttpServletRequest request
     * HandlerMethod handler
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    public ResponseEntity errorHandler(Throwable ex) {
        //指定异常处理
        String message;
        if (ex instanceof BizException) {
            //BizException异常返回
            message = ex.getMessage();
        } else if (ex instanceof BindException) {
            //validate异常返回
            StringBuffer stringBuffer = new StringBuffer();
            for (ObjectError objectError : ((BindException) ex).getBindingResult().getAllErrors()) {
                stringBuffer.append(objectError.getDefaultMessage()).append(",");
            }
            message = stringBuffer.toString();
        } else {
            log.error("异常", ex);
            // 异常信息显示转换
            message = ex.getMessage();
            if (message == null || message.contains("Exception") || message.contains("### Error") || message.contains("exception")) {
                message = "处理异常";
            }
        }
        //3.响应异常结果
        R r = R.error(message);
        return new ResponseEntity<>(r, HttpStatus.OK);
    }
}
